﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using nplJobsBLL.ProcessJob;
using nplJobsBLL.ProcessJobSeeker;
using nplJobsBLL.ProcessSelectJobSeeker;
using nplJobsCommon.Common;
using nplJobsCommon.Employeer;
using nplJobsCommon.Job;
using nplJobsCommon.JobSeeker;
using nplJobsDAL.Select;
using Elmah;
using nplJobsBLL.Common;

public partial class JobSeeker_JobDetails : BasePage
{
    private string NEPAL_ID = WebConfigurationManager.AppSettings["NEPAL_ID"];//140 == Nepal
    private string KATHMANDU_ID = WebConfigurationManager.AppSettings["KATHMANDU_ID"];//29 == Kathmandu

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                if (Request.Params["jID"] == null)
                    return;

                try
                {
                    string encodeJobID = Request.Params["jID"].ToString();
                    string decodeJobID = Helper.Base64Decode(encodeJobID);

                    this.LoadData(Convert.ToInt32(decodeJobID));
                }
                catch (Exception ex) { }
                Page.Title = "npljobs.com || Job details";
            }

            pnlContactPerson.Visible = false;
            pnlContactPersonLoginMsg.Visible = false;
            if (HasAnyUserLoggedIn())
            {
                pnlContactPerson.Visible = true;
            }
            else
                pnlContactPersonLoginMsg.Visible = true;
        }
        catch (System.Threading.ThreadAbortException)
        {
        } 
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
    }

    protected void btnApply_Click(object sender, EventArgs e)
    {
        string jID = Request.Params["jID"].ToString();

        if (Session["jobseeker"] == null)
            Response.Redirect("~/JobSeeker/ApplyOnline.aspx?jID=" + jID);
        else
            Response.Redirect("~/JobSeeker/ApplyOnlineStep2.aspx?jID=" + jID);
    }

    protected void lnkSavePdf_OnClick(object sender, EventArgs e)
    {
        try
        {
            pnlJob.Visible = true;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=job.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            pnlJob.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 50f, 30f, 50f, 30f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter docWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            PdfWriterEvents writerEvent = new PdfWriterEvents("www.npljobs.com");
            docWriter.PageEvent = writerEvent;
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
            pnlJob.Visible = false;
        }
        catch (System.Threading.ThreadAbortException)
        {

        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
    }

    protected string EducationalRequirements()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            string[] qualifications = job.Qualifications.Split('\n');
            foreach (string quali in qualifications)
            {
                if (!string.IsNullOrWhiteSpace(quali))
                    sb.Append(string.Format("<li>{0}</li>", quali));
            }
            if (string.IsNullOrEmpty(sb.ToString().Trim()))
                sb.Append("<li>N/A</li>");
        }
        return sb.ToString();
    }

    protected string Skills()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            string[] skills = job.Skills.Split('\n');
            foreach (string skill in skills)
            {
                if (!string.IsNullOrWhiteSpace(skill))
                    sb.Append(string.Format("<li>{0}</li>", skill));
            }
            if (string.IsNullOrEmpty(sb.ToString().Trim()))
                sb.Append("<li>N/A</li>");
        }
        return sb.ToString();
    }

    protected string JobDescription()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            string[] Responsibilities = job.JobResponsibilities.Split('\n');
            foreach (string res in Responsibilities)
            {
                if (!string.IsNullOrWhiteSpace(res))
                    sb.Append(string.Format("<li>{0}</li>", res));
            } 
            if (string.IsNullOrEmpty(sb.ToString().Trim()))
                sb.Append("<li>N/A</li>");
        }
        return sb.ToString();
    }

    protected string ExperienceRequirements()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            if (job.RequiredExperience.Equals(0)) //YES
            {
                if (job.TotalYearsOfExpMin.Equals(-1) && job.TotalYearsOfExpMax.Equals(-1))
                    sb.Append(string.Format("<li>Any year</li>"));
                else if (job.TotalYearsOfExpMin.Equals(-1) || job.TotalYearsOfExpMax.Equals(-1))
                    sb.Append(string.Format("<li>{0} to {1} year(s)</li>", job.TotalYearsOfExpMin.Equals(-1) ? "Any" : job.TotalYearsOfExpMin.ToString(), job.TotalYearsOfExpMax.Equals(-1) ? "Any" : job.TotalYearsOfExpMax.ToString()));
                else
                    sb.Append(string.Format("<li>{0} to {1} year(s)</li>", job.TotalYearsOfExpMin, job.TotalYearsOfExpMax));

                string[] ExperienceArea = job.ExperienceArea.Split('\n');
                foreach (string exp in ExperienceArea)
                {
                    sb.Append(string.Format("<li>{0}</li>", exp));
                }
            }
            else
            {
                sb.Append(string.Format("<li>{0}</li>", "No Requirement needed"));
            }
        }
        return sb.ToString();
    }

    protected string KnownLanguage()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            string[] KnownLanguage = job.KnownLanguage.Split(new char[] { ',' });
            foreach (string lan in KnownLanguage)
            {
                if (!string.IsNullOrWhiteSpace(lan))
                    sb.Append(string.Format("<li>{0}</li>", lan.Trim()));
            }
            if(string.IsNullOrEmpty(sb.ToString().Trim()))
                sb.Append("<li>N/A</li>");
        }
        return sb.ToString();
    }

    protected string OthersBenefit()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            string[] Benefits = job.Benefits.Split('\n');
            foreach (string benefit in Benefits)
            {
                if (!string.IsNullOrWhiteSpace(benefit))
                    sb.Append(string.Format("<li>{0}</li>", benefit.Trim()));
            }
            if (string.IsNullOrEmpty(sb.ToString().Trim()))
                sb.Append("<li>N/A</li>");
        }
        return sb.ToString();
    }

    protected string ApplyInstruction()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            string[] ApplicationInstructions = job.ApplicationInstructions.Split('\n');
            foreach (string instruction in ApplicationInstructions)
            {
                if (!string.IsNullOrWhiteSpace(instruction))
                    sb.Append(string.Format("{0}", instruction));
            }
            if (string.IsNullOrEmpty(sb.ToString().Trim()))
                sb.Append("<li>N/A</li>");
        }
        return sb.ToString();
    }

    protected string JobSource()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            sb.Append(string.Format("{0}", job.JobSource));
        }
        return sb.ToString();
    }

    protected string CandidateRequired()
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            if (job.AgeRangeFrom.Equals(-1) && job.AgeRangeTo.Equals(-1))
                sb.Append(string.Format("<li>Age any year</li>"));
            else if (job.AgeRangeFrom.Equals(-1) || job.AgeRangeTo.Equals(-1))
                sb.Append(string.Format("<li>{0} to {1} year(s)</li>", job.AgeRangeFrom.Equals(-1) ? "Any" : job.AgeRangeFrom.ToString(), job.AgeRangeTo.Equals(-1) ? "Any" : job.AgeRangeTo.ToString()));
            else
                sb.Append(string.Format("<li>Age {0} to {1} year(s)</li>", job.AgeRangeFrom, job.AgeRangeTo));

            if (job.Gender.Equals(0))
                sb.Append(string.Format("<li>Only males are allowed to apply</li>"));
            else if (job.Gender.Equals(1))
                sb.Append(string.Format("<li>Only females are allowed to apply</li>"));
            else if (job.Gender.Equals(2))
                sb.Append(string.Format("<li>Anyone are allowed to apply</li>"));
        }
        return sb.ToString();
    }

    Job job = null;
    private void LoadData(int jobID)
    {
        job = SelectJobList.GetJobDetails(jobID);
        if (job != null)
        {
            Session["Job"] = job;
            if (job.JobPublishStatus.Equals(-1) || job.JobPublishStatus.Equals(0) || job.JobPublishStatus.Equals(1))
            {
                Response.Redirect("../Default.aspx");
                return;
            }

            if (HttpContext.Current.Session["user"] != null && HttpContext.Current.Session["user"].Equals(General.Users.JobSeeker.ToString()))
            {
                not_registered.Style.Add("display", "none");
            }

            if (File.Exists(Server.MapPath(job.JobImagePath)))
            {
                imgNewJobImage.Attributes.Add("src", job.JobImagePath);
            }

            lblCompany.Text = job.CompanyName;
            lblCategory.Text = job.JobCategory;
            lblJobTitle.Text = job.JobTitle;
            lblNoOfVacancy.Text = job.Vacancies.ToString();
            lblReferenceNo.Text = string.IsNullOrWhiteSpace(job.InternalJobCode) ? "N/A" : job.InternalJobCode;
            if (job.SalaryRange.Equals(0))
                lblSalary.Text = "Negotiable";
            else if (job.SalaryRange.Equals(1))
                lblSalary.Text = "Don't want to mention";
            else
                lblSalary.Text = string.Format("{0} - {1} Npr/Month", job.SalaryRangeMin, job.SalaryRangeMax);

            lblWorkType.Text = job.JobType;

            string jobLevel = string.Empty;
            if ((job.CareerLevelID & 1) == 1)
                jobLevel = "Entry Level Job";
            if ((job.CareerLevelID & 2) == 2)
            {
                if (!string.IsNullOrEmpty(jobLevel))
                    jobLevel = jobLevel + ", ";
                jobLevel = jobLevel + "Mid Level Job";
            }
            if ((job.CareerLevelID & 4) == 4)
            {
                if (!string.IsNullOrEmpty(jobLevel))
                    jobLevel = jobLevel + ", ";
                jobLevel = jobLevel + "Top Level Job";
            }

            lblJobLevel.Text = string.IsNullOrWhiteSpace(jobLevel) ? "N/A" : jobLevel;

            if (job.JobLocationType.Equals(0)) //Anywhere in Nepal
                lblLocation.Text = " Anywhere in Nepal";
            else if (job.JobLocationType.Equals(1)) //Within Nepal
            {
                lblLocation.Text = SetCitiesWithinNepal(job.JobID);
            }
            else if (job.JobLocationType.Equals(2)) //Outside Nepal
            {
                lblLocation.Text = SetCitiesOutsideNepal(job.JobID);
            }

            lblPostedOn.Text = job.PostedDate.ToString("MMM dd, yyyy");
            lblPostedUntil.Text = Convert.ToDateTime(job.ApplicationDateline.ToShortDateString()) < Convert.ToDateTime(DateTime.Now.ToShortDateString()) ? "<span style='color:red;font-size: 14px;'>Expired</span>" : job.ApplicationDateline.ToString("MMM dd, yyyy");

            if (job.isHardCopy && job.isOnlineResume == false && job.isEmailAttachment == false)
            {
                divApplyButton.Style.Add("display", "none");
                divApplyButton2.Style.Add("display", "none");
            }

            lblApplicationDeadline.Text = job.ApplicationDateline.ToString("MMM dd, yyyy");

            Employeer employeer = nplJobsWebSite.Common.GetEmployeer(job.EmployeerID);
            if (employeer != null)
            {
                LoadJobInforForPDF(job, employeer);
                hfJobId.Value = job.JobID.ToString();
                hfEmployeerId.Value = job.EmployeerID.ToString();
                hfEmployeerName.Value = employeer.CompanyName;
                lblAdvertiser.Text = employeer.CompanyName;
                //lblCompanyName.Text = employeer.CompanyName;   

                if (string.IsNullOrEmpty(employeer.HomePageUrl))
                {
                    pnlCompanyWebLink2.Visible = false;
                }
                else
                {
                    lnkCompanyWebLink.Text = lnkCompanyWebLink2.Text = "Web : " + employeer.HomePageUrl;
                    lnkCompanyWebLink.Attributes["href"] = employeer.HomePageUrl;
                    lnkCompanyWebLink2.Attributes["href"] = employeer.HomePageUrl;
                    pnlCompanyWebLink2.Visible = true;
                }

                lblCompany.Text = employeer.CompanyName;

                if (!string.IsNullOrEmpty(employeer.CompanyDescription))
                {
                    pnlCompanyDescription2.Visible = true;
                    lblCompanyDescription.Text = lblCompanyDescription2.Text = employeer.CompanyDescription;
                }
                else
                {
                    pnlCompanyDescription2.Visible = false;
                }


                lblCompanyPhoneNo.Text = lblCompanyPhoneNo2.Text = (employeer.Phone.Length > 0 ? ("Ph: " + employeer.Phone) : string.Empty) + (employeer.Phone.Length > 0 && employeer.MobilePhone.Length > 0 ? ", " : string.Empty) + (employeer.MobilePhone.Length > 0 ? ("Mob: " + employeer.MobilePhone) : string.Empty);

                lblCompanyCityCountry.Text = lblCompanyCityCountry2.Text = job.CityName + (!string.IsNullOrEmpty(job.CityName) && !string.IsNullOrEmpty(job.CountryName) ? ", " : string.Empty) + job.CountryName;

                if (!string.IsNullOrEmpty(job.ContactPerson))
                {
                    lblContactPerson.Text = lblContactPerson2.Text = GetContactTitle(job.TitleID) + " " + job.ContactPerson;
                }
                else
                {
                    lblContactPerson.Visible = lblContactPerson2.Visible = false;
                }


                if (!string.IsNullOrEmpty(job.ContactPersonEmail))
                {
                    lblContactPersonEmail.Text = lblContactPersonEmail2.Text = "Email to: " + job.ContactPersonEmail;
                }
                else
                {
                    lblContactPersonEmail.Visible = lblContactPersonEmail2.Visible = false;
                }

                if (!string.IsNullOrEmpty(job.ContactPersonEmail))
                {
                    lblContactPersonPhone.Text = lblContactPersonPhone2.Text = "Ph: " + job.ContactPersonContactNumber;
                }
                else
                {
                    lblContactPersonPhone.Visible = lblContactPersonPhone2.Visible = false;
                }

                if (!string.IsNullOrEmpty(job.ContactPersonContactNumber))
                {
                    if (!string.IsNullOrEmpty(job.ContactPersonAlternativeNumber))
                        lblContactPersonPhone.Text = job.ContactPersonContactNumber + ", " + job.ContactPersonAlternativeNumber;
                }

                if (!job.IsPhotoEnclosed)
                    EnclosePhotograph.Style.Add("display", "none");

                if (!job.IsCompanyInfoVisible)
                {
                    if (!string.IsNullOrEmpty(employeer.Address.Trim()))
                    {
                        string cityName = employeer.Country == 0 ? GetCity(Convert.ToInt32(NEPAL_ID), Convert.ToInt32(KATHMANDU_ID), employeer.CityName) : GetCity(employeer.Country, employeer.City, employeer.CityName);
                        string countryName = employeer.Country == 0 ? GetCountry(Convert.ToInt32(NEPAL_ID)) : GetCountry(employeer.Country);

                        lblCompanyAddress.Text = lblCompanyAddress2.Text = string.Format("{0}{1}{2}{3}.", "GPO Box: ", employeer.Address, string.IsNullOrEmpty(cityName) ? string.Empty : ", " + cityName, string.IsNullOrEmpty(countryName) ? string.Empty : ", " + countryName);

                        divCompanyAddress.Style.Add("display", "block");
                        divCompanyAddress2.Style.Add("display", "block");
                    }
                }
            }

            if (job.JobPublishStatus.Equals(99) && Convert.ToDateTime(job.ApplicationDateline.ToShortDateString()) < Convert.ToDateTime(DateTime.Now.ToShortDateString()))
            {
                btnApply1.Visible = btnApply.Visible = false;
                pnlContactPerson.Visible = true;
                lblContactPersonEmail2.Visible = lblContactPersonPhone2.Visible = false;
                lblContactPerson2.Text = "Not Applicable";
            }
        }
        else
        {
            Response.Redirect("../Default.aspx");
            return;
        }
    }

    private string GetCountry(int countryId)
    {
        ProcessCountry country = new ProcessCountry();
        country.invoke();
        List<Country> lstCountry = country.Country.Where(c => c.ID == countryId).ToList();
        if (lstCountry.Count > 0)
        {
            return lstCountry[0].Name;
        }
        return string.Empty;
    }

    private string GetCity(int countryId, long cityId, string defaultCity)
    {
        ProcessSelectCity city = new ProcessSelectCity();
        city.countryID = countryId;
        city.invoke();

        City cty = city.City.Where(c => c.ID == cityId).FirstOrDefault();
        if (cty != null)
        {
            return cty.Name;
        }
        else
            return defaultCity;
    }

    private string GetContactTitle(int TitleID)
    {
        string result = string.Empty;
        if (TitleID == 1)
            result = "Mr.";
        else if (TitleID == 2)
            result = "Mrs.";
        else if (TitleID == 3)
            result = "Miss.";
        else if (TitleID == 4)
            result = "Ms.";

        return result;
    }

    private void LoadJobInforForPDF(Job job, Employeer employeer)
    {
        StringBuilder sb = new StringBuilder();

        lblPdfCompanyName.Text = employeer.CompanyName;
        lblPdfCompanyInformation.Text = employeer.CompanyDescription;
        lblPdfURL.Text = employeer.HomePageUrl;

        if (!string.IsNullOrEmpty(job.JobCategory))
        {
            lblPdfJobCategory.Text = job.JobCategory;
            trCategoryText.Visible = true;
            trCategoryTitle.Visible = true;
        }
        else
        {
            trCategoryText.Visible = false;
            trCategoryTitle.Visible = false;
        }

        string vacancy = job.JobTitle + " (" + job.Vacancies + ")";

        if (!string.IsNullOrEmpty(vacancy))
        {
            lblPdfTitle.Text = vacancy;
            trVacancyTitle.Visible = true;
            trVacancyTitle.Visible = true;
        }
        else
        {
            trVacancyTitle.Visible = false;
            trVacancyTitle.Visible = false;
        }
        //lblPdfInternalCode.Text = job.InternalJobCode;
        string description = JobDescription(job);
        lblPdfJobDescription.Text = description;
        if (!string.IsNullOrEmpty(description))
        {
            trDescriptionTitle.Visible = true;
            trDescriptionText.Visible = true;
        }
        else
        {
            trDescriptionTitle.Visible = false;
            trDescriptionText.Visible = false;
        }

        string educationInfo = string.Empty;
        if (job != null)
        {
            string[] qualifications = job.Qualifications.Split('\n');
            foreach (string quali in qualifications)
            {
                sb.Append(string.Format("<li style='margin-left: -10px !important;'>{0}</li>", quali));
            }
            educationInfo = sb.ToString();
            lblPdfEducation.Text = educationInfo;
        }
        string skillss = Skills(job);
        lblPdfSkills.Text = skillss;

        if (!string.IsNullOrEmpty(educationInfo) && !string.IsNullOrEmpty(skillss))
        {
            trEducationTitle.Visible = true;
            trEducationText.Visible = true;
        }
        else
        {
            trEducationTitle.Visible = false;
            trEducationText.Visible = false;
        }

        sb = new StringBuilder();
        //string[] KnownLanguage = job.KnownLanguage.Split('\n');
        string[] KnownLanguage = job.KnownLanguage.Split(new char[] { ',' });

        foreach (string lan in KnownLanguage)
        {
            sb.Append(string.Format("<li style='margin-left: -10px !important;'>{0}</li>", lan.Trim()));
        }
        if (KnownLanguage != null && KnownLanguage.Count() > 0 && KnownLanguage[0].ToString() != "")
        {
            trLanguagesRequiredTitle.Visible = true;
            trLanguagesRequiredText.Visible = true;
            lblPdfLanguages.Text = sb.ToString();
        }
        else
        {
            trLanguagesRequiredTitle.Visible = false;
            trLanguagesRequiredText.Visible = false;
        }
        string knowledgeExperience = ExperienceRequirements(job);

        if (!string.IsNullOrEmpty(knowledgeExperience))
        {
            lblPdfExperienceArea.Text = knowledgeExperience;
            trKnowledgeText.Visible = true;
            trKnowledgeTitle.Visible = true;
        }
        else
        {
            trKnowledgeText.Visible = false;
            trKnowledgeTitle.Visible = false;
        }

        ////////////////Candidate Required///////////////////
        sb = new StringBuilder();
        if (job.AgeRangeFrom.Equals(-1) && job.AgeRangeTo.Equals(-1))
            sb.Append(string.Format("<li>Age any year</li>"));
        else if (job.AgeRangeFrom.Equals(-1) || job.AgeRangeTo.Equals(-1))
            sb.Append(string.Format("<li>{0} to {1} year(s)</li>", job.AgeRangeFrom.Equals(-1) ? "Any" : job.AgeRangeFrom.ToString(), job.AgeRangeTo.Equals(-1) ? "Any" : job.AgeRangeTo.ToString()));
        else
            sb.Append(string.Format("<li>Age {0} to {1} year(s)</li>", job.AgeRangeFrom, job.AgeRangeTo));

        if (job.Gender.Equals(0))
            sb.Append(string.Format("<li>Only males are allowed to apply</li>"));
        else if (job.Gender.Equals(1))
            sb.Append(string.Format("<li>Only females are allowed to apply</li>"));
        else if (job.Gender.Equals(2))
            sb.Append(string.Format("<li>Anyone are allowed to apply</li>"));

        if (!string.IsNullOrEmpty(sb.ToString()))
        {
            lblPdfYearsGender.Text = sb.ToString();
            trSpecialRequirementsTitle.Visible = true;
            trSpecialRequirementsTitle.Visible = true;
        }
        else
        {
            trSpecialRequirementsTitle.Visible = false;
            trSpecialRequirementsTitle.Visible = false;
        }
        /////////////////Benefits////////////////////////
        sb = new StringBuilder();
        string[] Benefits = job.Benefits.Split('\n');
        foreach (string benefit in Benefits)
        {
            sb.Append(string.Format("<li>{0}</li>", benefit));
        }
        if (Benefits != null && Benefits.Count() > 0 && Benefits[0].ToString() != "")
        {
            lblPdfBenefits.Text = sb.ToString();
            trBenefitsTitle.Visible = true;
            trBenefitsText.Visible = true;
        }
        else
        {
            trBenefitsTitle.Visible = false;
            trBenefitsText.Visible = false;
        }
        /////////////////Job Location////////////////////////
        if (job.JobLocationType.Equals(0)) //Anywhere in Nepal
            lblPdfJobLocation.Text = "Anywhere in Nepal";
        else if (job.JobLocationType.Equals(1)) //Within Nepal
        {
            lblPdfJobLocation.Text = SetCitiesWithinNepal(job.JobID);
        }
        else if (job.JobLocationType.Equals(2)) //Outside Nepal
        {
            lblPdfJobLocation.Text = SetCitiesOutsideNepal(job.JobID);
        }
        ////////////////Salary////////////////////////
        if (job.SalaryRange.Equals(0))
            lblPdfSalary.Text = "Negotiable";
        else if (job.SalaryRange.Equals(1))
            lblPdfSalary.Text = "Don't want to mention";
        else
            lblPdfSalary.Text = string.Format("{0} - {1} NPR/Month", job.SalaryRangeMin, job.SalaryRangeMax);

        string salary = lblPdfSalary.Text;

        if (!string.IsNullOrEmpty(salary))
        {
            trSalaryTitle.Visible = true;
            trSalaryTitle.Visible = true;
        }
        else
        {
            trSalaryTitle.Visible = false;
            trSalaryTitle.Visible = false;
        }

        lblPdfWorkNature.Text = job.JobType;

        if (!string.IsNullOrEmpty(lblPdfWorkNature.Text) || !string.IsNullOrEmpty(lblPdfJobLevel.Text))
        {
            trWorkNatureTitle.Visible = true;
            trWorkNatureText.Visible = true;
        }
        else
        {
            trWorkNatureTitle.Visible = false;
            trWorkNatureText.Visible = false;
        }


        ////////////////Job Level////////////////////////
        string jobLevel = string.Empty;
        if ((job.CareerLevelID & 1) == 1)
            jobLevel = "Entry Level Job";
        if ((job.CareerLevelID & 2) == 2)
        {
            if (!string.IsNullOrEmpty(jobLevel))
                jobLevel = jobLevel + ", ";
            jobLevel = jobLevel + "Mid Level Job";
        }
        if ((job.CareerLevelID & 4) == 4)
        {
            if (!string.IsNullOrEmpty(jobLevel))
                jobLevel = jobLevel + ", ";
            jobLevel = jobLevel + "Top Level Job";
        }
        lblPdfJobLevel.Text = jobLevel;

        if (!string.IsNullOrEmpty(lblPdfDeadline.Text))
        {
            trDeadlineTitle.Visible = true;
            trDeadlineText.Visible = true;
        }
        else
        {
            trDeadlineTitle.Visible = false;
            trDeadlineText.Visible = false;
        }

        lblPdfDeadline.Text = job.ApplicationDateline.ToString("dd/MM/yyyy");

        if (!string.IsNullOrEmpty(lblPdfDeadline.Text))
        {
            trDeadlineTitle.Visible = true;
            trDeadlineText.Visible = true;
        }
        else
        {
            trDeadlineTitle.Visible = false;
            trDeadlineText.Visible = false;
        }

        lblPdfJobSource.Text = job.JobSource;

        if (!string.IsNullOrEmpty(lblPdfJobSource.Text))
        {
            trJobSourceTitle.Visible = true;
            trJobSourceText.Visible = true;
        }
        else
        {
            trJobSourceTitle.Visible = false;
            trJobSourceText.Visible = false;
        }

        if (!job.IsCompanyInfoVisible)
        {
            lblPostalAddress.Text = "GPO Box: " + employeer.Address;


            if (!string.IsNullOrEmpty(employeer.Address))
            {
                trPostalAddressText.Visible = true;
                trPostalAddressTitle.Visible = true;
            }
            else
            {
                trPostalAddressText.Visible = false;
                trPostalAddressTitle.Visible = false;
            }
        }

    }

    private string SetCitiesOutsideNepal(long jobId)
    {
        StringBuilder txt = new StringBuilder();
        ProcessSelectCitiesByJob jobCities = new ProcessSelectCitiesByJob();
        jobCities.JobID = jobId;
        jobCities.InvokeOutsideCities();
        List<JobCities> lstJobCities = jobCities.JobCities;

        var distinctCountry = (from jc in lstJobCities
                               select jc.CountryID).Distinct();
        foreach (var coun in distinctCountry)
        {
            var filterJC = lstJobCities.Where(w => w.CountryID.Equals(coun));
            foreach (var filter in filterJC)
            {
                if (!string.IsNullOrEmpty(filter.CityName))
                {
                    txt.AppendFormat("{0}, ", filter.CityName);
                }
            }
            if (filterJC.Count() > 0)
                txt.AppendFormat("{0} </br>: ", filterJC.FirstOrDefault().CountryName);
        }
        string str = txt.ToString();
        return str.Length > 0 ? str.Trim().Substring(0, str.Length - 1) : str;
    }

    private string SetCitiesWithinNepal(long jobId)
    {
        StringBuilder txt = new StringBuilder();
        ProcessSelectCitiesByJob jobCities = new ProcessSelectCitiesByJob();
        jobCities.JobID = jobId;
        jobCities.invoke();
        List<JobCities> lstJobCities = jobCities.JobCities;

        var distinctDistrict = (from jc in lstJobCities
                                select jc.DistrictID).Distinct();
        foreach (var dist in distinctDistrict)
        {
            var filterJC = lstJobCities.Where(w => w.DistrictID.Equals(dist));
            foreach (var filter in filterJC)
            {
                if (!string.IsNullOrEmpty(filter.CityName))
                {
                    txt.AppendFormat("{0}, ", filter.CityName);
                }
            }
            if (filterJC.Count() > 0)
                txt.AppendFormat("{0} </br>: ", filterJC.FirstOrDefault().DistrictName);
        }
        string str = txt.ToString().Trim();
        return str.Length > 0 ? str.Substring(0, str.Length - 1) : str;
    }

    public bool HasAnyUserLoggedIn()
    {
        if (HttpContext.Current.Session["user"] != null && (HttpContext.Current.Session["user"].Equals(General.Users.JobSeeker.ToString()) || HttpContext.Current.Session["user"].Equals(General.Users.Employeer.ToString())))
            return true;
        else
            return false;
    }

    #region TemplateFriendEMail
    private static bool SentEmailNotification(string jobId, string jobSeekerEmailAddress, string friendsEmailAddress, out string error)
    {
        error = string.Empty;
        bool flag = false;
        try
        {
            var fromAddress = WebConfigurationManager.AppSettings["ALERT_EMAIL_FROM_ADDRESS"];
            var fromPassword = WebConfigurationManager.AppSettings["ALERT_EMAIL_FROM_PASSWORD"];
            var smtpAddress = WebConfigurationManager.AppSettings["SMTP_ADDRESS"];
            var smtPort = WebConfigurationManager.AppSettings["SMTP_PORT"];
            string subject = "npljobs.com.Job Information";

            /////////////Get Body///////////
            string body = GetBodyTemplate(jobId, jobSeekerEmailAddress);

            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(fromAddress, friendsEmailAddress, subject, body);
            mail.IsBodyHtml = true;

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
            smtp.Host = smtpAddress;
            smtp.Port = Convert.ToInt32(smtPort);
            smtp.UseDefaultCredentials = false;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);
            smtp.EnableSsl = false;
            smtp.Send(mail);
            flag = true;
        }
        catch (Exception ex)
        {
            flag = false;
            error = ex.Message;
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return flag;
    }

    private static string GetBodyTemplate(string jobID, string jobSeekerEmailAddress)
    {
        Job job = null;
        if (HttpContext.Current.Session["Job"] != null)
            job = (Job)HttpContext.Current.Session["Job"];

        if (job == null)
            job = SelectJobList.GetJobDetails(int.Parse(jobID));

        if (job != null)
        {
            var template = new EmailTemplate("~/JobSeeker/EmailTemplates/ucJobDetails.ascx");
            template.Tags.Add("JobId", job.JobID.ToString());
            template.Tags.Add("JobTitle", job.JobTitle);
            template.Tags.Add("PostedOn", job.PostedDate.ToString("MMM dd, yyyy"));
            template.Tags.Add("JobSeekerEmailAddress", jobSeekerEmailAddress);
            template.Tags.Add("JobDescription", JobDescription(job));
            template.Tags.Add("Skills", Skills(job));
            template.Tags.Add("ExperienceRequirements", ExperienceRequirements(job));
            template.Tags.Add("Deadline", job.ApplicationDateline.ToString("MMM dd, yyyy"));
            template.Tags.Add("JobReference", job.InternalJobCode);

            Employeer employeer = nplJobsWebSite.Common.GetEmployeer(job.EmployeerID);
            if (employeer != null)
            {
                template.Tags.Add("CompanyName", employeer.CompanyName);
                template.Tags.Add("CompanyWebAddress", employeer.HomePageUrl);
            }
            return template.Render();
        }
        return string.Empty;
    }

    private static string Skills(Job job)
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            string[] skills = job.Skills.Split('\n');
            foreach (string skill in skills)
            {
                if (!string.IsNullOrEmpty(skill))
                    sb.Append(string.Format("<li style='margin-left: -10px !important;'>{0}</li>", skill));
            }
        }
        return sb.ToString();
    }

    private static string JobDescription(Job job)
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            string[] Responsibilities = job.JobResponsibilities.Split('\n');
            foreach (string res in Responsibilities)
            {
                if (!string.IsNullOrEmpty(res))
                    sb.Append(string.Format("<li style='margin-left: -10px;'>{0}</li>", res));
            }
        }
        return sb.ToString();
    }

    private static string ExperienceRequirements(Job job)
    {
        StringBuilder sb = new StringBuilder();
        if (job != null)
        {
            if (job.RequiredExperience.Equals(0)) //YES
            {
                if (job.TotalYearsOfExpMin.Equals(-1) && job.TotalYearsOfExpMax.Equals(-1))
                    sb.Append(string.Format("<li style='margin-left: -10px;'>Any year</li>"));
                else if (job.TotalYearsOfExpMin.Equals(-1) || job.TotalYearsOfExpMax.Equals(-1))
                    sb.Append(string.Format("<li style='margin-left: -10px;'>{0} to {1} year(s)</li>", job.TotalYearsOfExpMin.Equals(-1) ? "Any" : job.TotalYearsOfExpMin.ToString(), job.TotalYearsOfExpMax.Equals(-1) ? "Any" : job.TotalYearsOfExpMax.ToString()));
                else
                    sb.Append(string.Format("<li style='margin-left: -10px;'>{0} to {1} year(s)</li>", job.TotalYearsOfExpMin, job.TotalYearsOfExpMax));

                string[] ExperienceArea = job.ExperienceArea.Split('\n');
                foreach (string exp in ExperienceArea)
                {
                    if (!string.IsNullOrEmpty(exp))
                        sb.Append(string.Format("<li style='margin-left: -10px;'>{0}</li>", exp));
                }
            }
            else
            {
                sb.Append(string.Format("<li style='margin-left: -10px;'>{0}</li>", "No Requirement needed"));
            }
        }
        return sb.ToString();
    }

    #endregion

    #region TemplateEmailToEmployeer
    private static bool SentEmailNotificationToEmployeer(Guid JobSeekerID, string companyID, string jobId, string expectedSalary, out string error)
    {
        error = string.Empty;
        bool flag = false;
        try
        {
            var fromAddress = WebConfigurationManager.AppSettings["ALERT_EMAIL_FROM_ADDRESS"];
            var fromPassword = WebConfigurationManager.AppSettings["ALERT_EMAIL_FROM_PASSWORD"];
            var smtpAddress = WebConfigurationManager.AppSettings["SMTP_ADDRESS"];
            var smtPort = WebConfigurationManager.AppSettings["SMTP_PORT"];

            Employeer employeer = nplJobsWebSite.Common.GetEmployeer(Guid.Parse(companyID));
            if (employeer != null)
            {
                JobSeeker jobSeeker = GetJobSeeker(JobSeekerID);

                Job job = SelectJobList.GetJobDetails(int.Parse(jobId));
                if (job != null)
                {
                    ///////////////Get Body///////////
                    string body = GetJobSeekerBodyTemplate(jobSeeker, employeer, job, expectedSalary);
                    string subject = string.Format("Application for {0}", job.JobTitle);

                    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(fromAddress, employeer.Email, subject, body);
                    mail.Bcc.Add("manobesh1982@gmail.com");

                    if (!string.IsNullOrEmpty(job.ContactPersonEmail))
                        mail.CC.Add(job.ContactPersonEmail);

                    try
                    {
                        if (jobSeeker != null && !string.IsNullOrEmpty(jobSeeker.Resume))
                        {
                            string fileName = HttpContext.Current.Server.MapPath("~/UploadedResume/" + jobSeeker.Resume);

                            if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
                                mail.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath("~/UploadedResume/" + jobSeeker.Resume)));
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorSignal.FromCurrentContext().Raise(ex);
                    }
                    mail.IsBodyHtml = true;

                    System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                    smtp.Host = smtpAddress;
                    smtp.Port = Convert.ToInt32(smtPort);
                    smtp.UseDefaultCredentials = false;
                    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtp.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);
                    smtp.EnableSsl = false;
                    smtp.Send(mail);
                    flag = true;
                }
            }
        }
        catch (Exception ex)
        {
            flag = false;
            error = ex.Message;
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return flag;
    }

    private static string GetJobSeekerBodyTemplate(JobSeeker jobSeeker, Employeer employeer, Job job, string expectedSalary)
    {
        if (jobSeeker != null)
        {
            var template = new EmailTemplate("~/JobSeeker/EmailTemplates/ucJobSeekerDetails.ascx");
            template.Tags.Add("JobSeekerSummary", jobSeeker.AboutMe);
            template.Tags.Add("JobSeekerExperience", JobSeekerExperience(jobSeeker.JobSeekerID));
            template.Tags.Add("JobSeekerEducation", JobSeekerEducation(jobSeeker.JobSeekerID));
            template.Tags.Add("JobSeekerQualification", JobSeekerQualification(jobSeeker));
            template.Tags.Add("JobSeekerSkills", JobSeekerSkills(jobSeeker));
            template.Tags.Add("JobSeekerSkillsPlain", JobSeekerSkillsPlain(jobSeeker));
            template.Tags.Add("JobSeekerLanguageProficiency", JobSeekerLanguageProficiency(jobSeeker.JobSeekerID));
            template.Tags.Add("JobSeekerContactMobile", jobSeeker.MobilePhone);
            template.Tags.Add("JobSeekerHomePhone", jobSeeker.HomePhone);
            template.Tags.Add("JobSeekerEmail", jobSeeker.Email);
            template.Tags.Add("JobSeekerAlternativeEmail", jobSeeker.AlternativeEmail);
            template.Tags.Add("PresentAddress", string.Format("{0} {1} {2} {3}", jobSeeker.PostalAddress + ",", string.IsNullOrEmpty(jobSeeker.District) ? string.Empty : jobSeeker.District + ",", string.IsNullOrEmpty(jobSeeker.City) ? string.Empty : jobSeeker.City + ",", jobSeeker.Country));
            template.Tags.Add("JobSeekerPresentSalary", jobSeeker.PresentSalaryRange);
            template.Tags.Add("JobSeekerExpectedSalary", expectedSalary);


            template.Tags.Add("JobSeekerFullName", string.Format("{0} {1}", jobSeeker.FirstName, jobSeeker.LastName));
            if (jobSeeker.Resume != null && jobSeeker.Resume.Length > 4)
                template.Tags.Add("Resume", "YES");
            else
                template.Tags.Add("Resume", "NO");

            if (!string.IsNullOrEmpty(job.ContactPerson))
                template.Tags.Add("Employeer", ((job.TitleID == 0 || job.TitleID == -1) ? string.Empty : job.Title + " ") + job.ContactPerson);
            else
                template.Tags.Add("Employeer", employeer.CompanyName);

            return template.Render();
        }
        return string.Empty;
    }

    public static string SendEMailToEmployeer(Guid JobSeekerID, string companyID, string jobId, string expectedSalary)
    {
        Guid employeerId = Guid.Parse(companyID.ToString());
        string error = string.Empty;
        SentEmailNotificationToEmployeer(JobSeekerID, companyID, jobId, expectedSalary, out error);
        return error;
    }

    private static string JobSeekerExperience(Guid JobSeekerID)
    {
        StringBuilder sb = new StringBuilder();
        ProcessSelectProfessionalInfo sp = new ProcessSelectProfessionalInfo();
        sp.ProfessionalInfoID = -1;
        sp.JobseekerID = JobSeekerID;
        sp.invoke();
        List<ProfessionalInfo> pInfo = sp.ProfessionalInfo;

        for (int i = 0; i < pInfo.Count; i++)
        {
            sb.Append(string.Format("<li><span style='font-size: 14px;'>Company Name: <strong>{0}</strong></span></li>", pInfo[i].CompanyName));
            sb.Append(string.Format("<li><span style='font-size: 14px;'>Position: {0}</span></li>", pInfo[i].Title));
            sb.Append(string.Format("<li><span style='font-size: 14px;'>Position Description: {0}</span></li>", pInfo[i].PositionDescription));

            if (i < pInfo.Count)
                sb.Append("<br />");
        }
        return sb.ToString();
    }

    private static string JobSeekerEducation(Guid JobSeekerID)
    {
        StringBuilder sb = new StringBuilder();
        ProcessSelectEducationalInfo ei = new ProcessSelectEducationalInfo();
        ei.EducationalInfoID = -1;
        ei.JobseekerID = JobSeekerID;
        ei.invoke();
        List<EducationInfo> eiInfo = ei.EducationalInfo;

        for (int i = 0; i < eiInfo.Count; i++)
        {
            sb.Append(string.Format("<li><span style='font-size: 14px;'>Institution Name: <strong>{0}</strong></span></li>", eiInfo[i].InstitutionName));
            sb.Append(string.Format("<li><span style='font-size: 14px;'>Degree: {0}</span></li>", eiInfo[i].Degree));
            sb.Append(string.Format("<li><span style='font-size: 14px;'>Specialized Subjects: {0}</span></li>", eiInfo[i].SpecializedSubjects));

            if (i < eiInfo.Count)
                sb.Append("<br />");
        }
        return sb.ToString();
    }

    private static string JobSeekerQualification(JobSeeker jobSeeker)
    {
        StringBuilder sb = new StringBuilder();
        if (jobSeeker.Qualifications != null)
        {
            string[] Qualifications = jobSeeker.Qualifications.Split('~');
            foreach (string quali in Qualifications)
            {
                if (quali.Length > 0)
                    sb.Append(string.Format("<li><span style='font-size: 14px;'>{0}</span></li>", quali));
            }
        }
        return sb.ToString();
    }

    private static string JobSeekerSkillsPlain(JobSeeker jobSeeker)
    {
        string skillsPlain = string.Empty;

        if (jobSeeker.Skills != null)
        {
            skillsPlain = jobSeeker.Skills;
        }
        return skillsPlain;
    }
    private static string JobSeekerSkills(JobSeeker jobSeeker)
    {
        StringBuilder sb = new StringBuilder();
        if (jobSeeker.Skills != null)
        {
            string[] Skills = jobSeeker.Skills.Split(',');
            foreach (string skill in Skills)
            {
                if (skill.Length > 0)
                    sb.Append(string.Format("<li><span style='font-size: 14px;'>{0}</span></li>", skill));
            }
        }
        return sb.ToString();
    }

    private static string JobSeekerLanguageProficiency(Guid JobSeekerID)
    {
        StringBuilder sb = new StringBuilder();
        ProcessSelectJobSeekerLanguageProficiency ei = new ProcessSelectJobSeekerLanguageProficiency();
        ei.JobSeekerID = JobSeekerID;
        ei.invoke();
        List<JobSeekerLanguageProficiency> lstLanPro = ei.JobSeekerLanguageProficiency;

        foreach (JobSeekerLanguageProficiency lanPro in lstLanPro)
        {
            sb.Append(string.Format("<li><span style='font-size: 14px;'>{0} : {1}</span></li>", lanPro.Language, lanPro.Proficiency));
        }
        return sb.ToString();
    }

    #endregion

    private static JobSeeker GetJobSeeker(Guid jobSeekerId)
    {
        JobSeeker jobSeeker = new JobSeeker();
        ProcessSelectJobSeeker selectJobSeeker = new ProcessSelectJobSeeker();

        selectJobSeeker.JobSeekerID = jobSeekerId;
        selectJobSeeker.invoke();

        if (selectJobSeeker.JobSeeker != null)
        {
            jobSeeker = selectJobSeeker.JobSeeker.FirstOrDefault();
        }

        return jobSeeker;
    }

    #region WebMethod
    [WebMethod(EnableSession = true)]
    public static string GetCompanyJobs(string companyID, string jobId)
    {
        if (!string.IsNullOrEmpty(companyID))
        {
            int jobID = int.Parse(jobId);

            List<Job> jobList = SelectJobList.GetJobDetails(Guid.Parse(companyID)).Where(wh => wh.JobPublishStatus.Equals(99) && wh.ApplicationDateline >= DateTime.Now && !wh.JobID.Equals(jobID)).ToList();// 
            foreach (Job j in jobList)
                j.EncodeJobID = Helper.Base64Encode(j.JobID.ToString());
            return new JavaScriptSerializer().Serialize(jobList);
        }
        return string.Empty;
    }

    [WebMethod(EnableSession = true)]
    public static int GetCountCompanyJobs(string companyID)
    {
        if (!string.IsNullOrEmpty(companyID))
        {
            List<Job> jobList = SelectJobList.GetJobDetails(Guid.Parse(companyID)).Where(wh => wh.JobPublishStatus.Equals(99)).ToList();
            return jobList.Count;
        }
        return 0;
    }

    [WebMethod(EnableSession = true)]
    public static string HasJobSeekerLoggedIn()
    {
        if (HttpContext.Current.Session["user"] != null && HttpContext.Current.Session["user"].Equals(General.Users.JobSeeker.ToString()))
            return ((System.Web.Security.MembershipUser)HttpContext.Current.Session["userInfo"]).UserName;
        else
            return string.Empty;
    }

    [WebMethod(EnableSession = true)]
    public static string GetJobSeekerLoggedInContactInfor()
    {
        if (HttpContext.Current.Session["jobseeker"] != null && HttpContext.Current.Session["user"] != null && HttpContext.Current.Session["user"].Equals(General.Users.JobSeeker.ToString()))
            return new JavaScriptSerializer().Serialize(((JobSeeker)HttpContext.Current.Session["jobseeker"]));
        else
            return string.Empty;
    }

    [WebMethod(EnableSession = true)]
    public static bool GetJobSeekerLoggedIn(string userName, string password)
    {
        if (System.Web.Security.Membership.ValidateUser(userName, password))
        {
            System.Web.Security.MembershipUser userInfo = System.Web.Security.Membership.GetUser(userName);
            if (userInfo != null)
            {
                Guid userID = (Guid)userInfo.ProviderUserKey;
                JobSeeker jobSeeker = GetJobSeeker(userID);
                if (jobSeeker != null)
                {
                    HttpContext.Current.Session["UserID"] = jobSeeker.JobSeekerID;
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddDays(1), false, "JobSeekerData", FormsAuthentication.FormsCookiePath);

                    string encTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie hc = new HttpCookie("AuthCookJobSeeker", encTicket);
                    hc.Expires = ticket.Expiration;
                    HttpContext.Current.Response.Cookies.Add(hc);

                    HttpContext.Current.Response.Cookies["JobSeekerUserName"].Value = userName;
                    HttpContext.Current.Response.Cookies["JobSeekerPassword"].Value = password;
                    bool isRemembered = true;
                    HttpContext.Current.Response.Cookies["JobSeekerRememberMe"].Value = isRemembered.ToString();

                    FormsAuthentication.SetAuthCookie(userName, true);

                    if (isRemembered)
                    {
                        HttpContext.Current.Response.Cookies["JobSeekerUserName"].Expires = DateTime.Now.AddDays(1);
                        HttpContext.Current.Response.Cookies["JobSeekerPassword"].Expires = DateTime.Now.AddDays(1);
                        HttpContext.Current.Response.Cookies["JobSeekerRememberMe"].Expires = DateTime.Now.AddDays(1);
                    }
                    else
                    {
                        HttpContext.Current.Response.Cookies["JobSeekerUserName"].Expires = DateTime.Now.AddDays(-1);
                        HttpContext.Current.Response.Cookies["JobSeekerPassword"].Expires = DateTime.Now.AddDays(-1);
                        HttpContext.Current.Response.Cookies["JobSeekerRememberMe"].Expires = DateTime.Now.AddDays(-1);
                    }

                    HttpContext.Current.Session["MoveToHomePage"] = "false";
                    HttpContext.Current.Session["userInfo"] = userInfo;
                    HttpContext.Current.Session["jobseeker"] = jobSeeker;
                    HttpContext.Current.Session["user"] = General.Users.JobSeeker.ToString();
                    return true;
                }
                else
                {
                    ClearAuthCookJobSeeker();
                }
            }
        }
        return false;
    }

    [WebMethod(EnableSession = true)]
    public static string SendEMailToFriend(string jobId, string jobSeekerEmailAddress, string friendsEmailAddress)
    {
        string error = string.Empty;
        SentEmailNotification(jobId, jobSeekerEmailAddress, friendsEmailAddress, out error);
        return error;
    }

    [WebMethod(EnableSession = true)]
    public static string ApplyOnlineJob(string jobId, string expectedSalary, string companyID)
    {
        string error = string.Empty;
        if (HttpContext.Current.Session["jobseeker"] != null)
        {
            try
            {
                Guid JobSeekerID = ((JobSeeker)HttpContext.Current.Session["jobseeker"]).JobSeekerID;
                if (ProcessJob.InsertAppliedJob(long.Parse(jobId), JobSeekerID, float.Parse(expectedSalary), DateTime.Now) > -1)
                {
                    SendEMailToEmployeer(JobSeekerID, companyID, jobId, expectedSalary);
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }
        return error;
    }

    [WebMethod(EnableSession = true)]
    public static string SavedJob(string jobId)
    {
        string error = string.Empty;
        if (HttpContext.Current.Session["jobseeker"] != null)
        {
            try
            {
                Guid JobSeekerID = ((JobSeeker)HttpContext.Current.Session["jobseeker"]).JobSeekerID;
                ProcessJob.InsertJobSeekerSavedJob(long.Parse(jobId), JobSeekerID);
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }
        return error;
    }

    [WebMethod(EnableSession = true)]
    public static bool RemovedJob(string jobId)
    {
        string error = string.Empty;
        if (HttpContext.Current.Session["jobseeker"] != null)
        {
            try
            {
                Guid JobSeekerID = ((JobSeeker)HttpContext.Current.Session["jobseeker"]).JobSeekerID;
                return ProcessJob.DeleteJobSeekerSavedJob(long.Parse(jobId), JobSeekerID);
            }
            catch (Exception ex)
            {
                error = ex.Message;
                ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }
        return false;
    }

    [WebMethod(EnableSession = true)]
    public static bool ShowHideSavedRemovedLinks(string jobId)
    {
        bool flag = false;
        if (HttpContext.Current.Session["jobseeker"] != null)
        {
            try
            {
                Guid JobSeekerID = ((JobSeeker)HttpContext.Current.Session["jobseeker"]).JobSeekerID;
                ProcessSavedJob processSavedJob = new ProcessSavedJob();
                SavedJob savedJob = processSavedJob.GetSavedJobs(int.Parse(jobId), JobSeekerID);
                if (savedJob != null)
                {
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                flag = false;
                ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }
        return flag;
    }

    #endregion

    #region ClearAuthCookJobSeeker
    private static void ClearAuthCookJobSeeker()
    {
        if (HttpContext.Current.Request.Cookies["AuthCookJobSeeker"] != null)
        {
            HttpCookie aCookie = HttpContext.Current.Request.Cookies["AuthCookJobSeeker"];
            aCookie.Values.Remove("JobSeekerUserName");
            aCookie.Values.Remove("JobSeekerPassword");
            aCookie.Values.Remove("JobSeekerRememberMe");
            aCookie.Expires = DateTime.Now.AddDays(-1d);
            HttpContext.Current.Response.Cookies.Add(aCookie);
        }
    }
    #endregion
}